package com.zhs.gccs.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import com.wwren.picture.lib.tools.BitmapUtils;
import com.zhs.gccs.R;
import com.zhs.gccs.model.WaterMaker;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

public class BitmapUtil extends BitmapUtils {

    public static Bitmap getBitmap(Context context, int res) {
        BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(res);
        return drawable.getBitmap();
    }

    /**
     * 读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap ReadBitmapById(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /***
     * 根据资源文件获取Bitmap
     *
     * @param context
     * @param drawableId
     * @return
     */
    public static Bitmap ReadBitmapById(Context context, int drawableId,
                                        int screenWidth, int screenHight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Config.ARGB_8888;
        options.inInputShareable = true;
        options.inPurgeable = true;
        InputStream stream = context.getResources().openRawResource(drawableId);
        Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
        return getBitmap(bitmap, screenWidth, screenHight);
    }

    public static Bitmap getBitmapFromFile(String localBrochurePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(localBrochurePath);
        return bitmap;
    }

    /***
     * 等比例压缩图片
     *
     * @param bitmap
     * @param screenWidth
     * @param screenHight
     * @return
     */
    public static Bitmap getBitmap(Bitmap bitmap, int screenWidth,
                                   int screenHight) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Log.e("jj", "图片宽度" + w + ",screenWidth=" + screenWidth);
        Matrix matrix = new Matrix();
        float scale = (float) screenWidth / w;
        float scale2 = (float) screenHight / h;

        // scale = scale < scale2 ? scale : scale2;

        // 保证图片不变形.
        matrix.postScale(scale, scale);
        // w,h是原图的属性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }

    /***
     * 保存图片至SD卡
     *
     * @param bm
     * @param url
     * @param quantity
     */
    private static int FREE_SD_SPACE_NEEDED_TO_CACHE = 1;
    private static int MB = 1024 * 1024;
    public final static String DIR = "/sdcard/fyjf";

    public static URI saveBmpToSd(Bitmap bm, String url, int quantity) {
        // 判断sdcard上的空间
        if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
            return null;
        }
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
            return null;
        String filename = url;
        // 目录不存在就创建
        File dirPath = new File(DIR);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        File file = new File(DIR + "/" + filename);
        try {
            file.createNewFile();
            OutputStream outStream = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);
            outStream.flush();
            outStream.close();
            bm.recycle();
            bm = null;
            return file.toURI();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 获取SD卡图片
     *
     * @param url
     * @param quantity
     * @return
     */
    @Deprecated
    public static Bitmap getBitmap(String url, int quantity) {
        InputStream inputStream = null;
        String filename = "";
        Bitmap map = null;
        URL url_Image = null;
        String LOCALURL = "";
        if (url == null)
            return null;
        try {
            filename = url;
        } catch (Exception err) {
        }

        LOCALURL = URLEncoder.encode(filename);
        if (Exist(DIR + "/" + LOCALURL)) {
            map = BitmapFactory.decodeFile(DIR + "/" + LOCALURL);
        } else {
            try {

                url_Image = new URL(url);
                inputStream = url_Image.openStream();
                map = BitmapFactory.decodeStream(inputStream);
                // url = URLEncoder.encode(url, "UTF-8");
                if (map != null) {
                    saveBmpToSd(map, LOCALURL, quantity);
                }
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return map;
    }
    ////注意该方法调研前不能有该文件，否则写入失败
    public static void saveBitmapFilePng(Bitmap bitmap, File file) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Deprecated
    public static Bitmap getUrlBitmap(String urlPath) {
        Bitmap map = null;
        try {
            URL url = new URL(urlPath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
            // TODO Auto-generated catch block
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /***
     * 判断图片是存在
     *
     * @param url
     * @return
     */
    public static boolean Exist(String url) {
        File file = new File(DIR + url);
        return file.exists();
    }

    /**
     * 计算sdcard上的剩余空间 * @return
     */
    private static int freeSpaceOnSd() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
                .getPath());
        double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
                .getBlockSize()) / MB;

        return (int) sdFreeMB;
    }


    /**
     * 合并两张bitmap为一张
     *
     * @param topImage
     * @param bottomImage
     * @return Bitmap
     */
    public static Bitmap combineBussicardBitmap(Bitmap topImage,
                                                Bitmap bottomImage,
                                                int topWidth,
                                                int topHeight,
                                                int bottomHeight) {
        if (topImage == null) {
            return null;
        }
        topImage = zoomImg(topImage, topWidth, topHeight);
        bottomImage = zoomImg(bottomImage, topWidth, bottomHeight);

//        int topWidth = topImage.getWidth();
//        int topHeight = topImage.getHeight();

//        int bottomWidth = bottomImage.getWidth();
        Bitmap newmap = Bitmap.createBitmap(
                topWidth,
                topHeight + bottomHeight,
                Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(topImage, 0, 0, null);
        canvas.drawBitmap(bottomImage, 0, topHeight, null);
        canvas.save();//Canvas.ALL_SAVE_FLAG
        canvas.restore();
        return newmap;
    }

    public static Bitmap combineBitmap(Bitmap topImage, Bitmap bottomImage) {
        if (topImage == null) {
            return null;
        }
//        topImage = zoomImg(topImage, 540, 960);
//        bottomImage = zoomImg(bottomImage, 540, 200);

        int topWidth = topImage.getWidth();
        int topHeight = topImage.getHeight();

        int bottomWidth = bottomImage.getWidth();
        int bottomHeight = bottomImage.getHeight();
        Bitmap newmap = Bitmap.createBitmap(topWidth, topHeight + bottomHeight, Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(topImage, 0, 0, null);
        canvas.drawBitmap(bottomImage, 0, topHeight, null);
        canvas.save();//Canvas.ALL_SAVE_FLAG
        canvas.restore();
        return newmap;
    }

    /**
     * 缩放bitmap
     *
     * @param bm
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    public static Bitmap createWatermark(Context context,Bitmap target, List<WaterMaker> waterMakers) {
        int w = target.getWidth();
        int h = target.getHeight();
//        Bitmap bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Bitmap bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Paint p = new Paint();
        // 水印的颜色
        p.setColor(Color.WHITE);
        // 水印的字体大小
        p.setTextSize(ScreenUtils.dpToPx(context,14));
        p.setAntiAlias(true);// 去锯齿
        canvas.drawBitmap(target, 0, 0, p);
        float marginBotton = ScreenUtils.dpToPx(context,16);
        float wordHeight = ScreenUtils.dpToPx(context,24);
        float wordMargin = ScreenUtils.dpToPx(context,8);
        float marginLeft = ScreenUtils.dpToPx(context,16);
        // 在中间位置开始添加水印
        for (int i=0;i<waterMakers.size();i++) {
            WaterMaker maker = waterMakers.get(i);
            String str = maker.getTag()+maker.getContent();
            float wh = marginBotton + (waterMakers.size()-i)*wordHeight + (waterMakers.size()-i-1)*wordMargin;
            canvas.drawText(str, marginLeft, h-wh, p);
        }
        canvas.save();//Canvas.ALL_SAVE_FLAG
        canvas.restore();
        return bmp;
    }


    // 为图片target添加水印
    private Bitmap createWatermarkBitmap(Bitmap target, String str) {
        int w = target.getWidth();
        int h = target.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Paint p = new Paint();
        // 水印的颜色
        p.setColor(Color.RED);
        // 水印的字体大小
        p.setTextSize(16);
        p.setAntiAlias(true);// 去锯齿
        canvas.drawBitmap(target, 0, 0, p);
        // 在中间位置开始添加水印
        canvas.drawText(str, w / 2, h / 2, p);
        canvas.save();//(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return bmp;
    }

}
